/**
 * 用户角色选择窗口
 */
var RoleSelectWin = (function(){
	
	var win = null;
	var schPanel = null
	var grid = null;
	var schUsername = '';
	var okBtn = null;
	
	var html = [
		'<div id="roleSelectPanel">'
			,'<div class="search-wrap">'
				,'<div class="search-content">'
					,'<table class="search-tab">'
						,'<tr>'
							,'<th>角色名:</th><td id="roleNameSch"></td>'
							,'<td>'
							,'<div id="btnRoleSch"></div>'
							,'</td>'
						,'</tr>'
					,'</table>'
				,'</div>'
			,'</div>'
				,'<div class="result-wrap">'
				,'<div class="result-content">'
					,'<div id="gridRole"></div>'
				,'</div>'
			,'</div>'
		,'</div>'
	];
					
	
	function init(callback) {
		if(!win) {
			initPanel();
			
			okBtn = new FDButton({text:'确定'})
			
			win = new FDWindow({
				contentId:'roleSelectPanel'
				,title:'选择角色'
				,width:'500px'
				,height:'350px'
				,modal:true  
				,buttons:[
					okBtn
					,new FDButton({text:'取消',onclick:function(){
						win.close();
					}})
				]
			});
		}
		okBtn.setOnclick(function(){
			ok(callback);
		});
	}
	
	function ok(callback) {
		var rows = grid.getChecked();
		var roleIds = [];
		if(rows && rows.length > 0){
			for(var i=0,len=rows.length;i<len;i++){
				roleIds.push(rows[i].roleId);
			}
			var params = {username:schUsername,roleIds:roleIds}
			Action.post(ctx + 'setUserRole.do',params ,function(e){
				if(e.success) {
					win.close();
					FDWindow.alert('角色设置成功');
					callback();
				}else{
					FDWindow.alert('设置失败');
				}
			});
			
		}else{
			FDWindow.alert('请选择角色');
		}
	}
	
	function initPanel() {
		var panel = html.join('');
		$('body').append(panel);
		
		schPanel = new FDFormPanel({
			controls:[
				new FDTextBox({domId:'roleNameSch',name:'roleNameSch'})
			]
		});
		
		new FDButton({domId:'btnRoleSch',text:'查询',onclick:function(){
			grid.search(schPanel.getValues());
		}});
		
		grid = new FDGrid({
			domId:'gridRole'
			,id:'roleId'
			,url:ctx + 'listAllRRole.do'
			,selectOption:{isMultiSelect:true}
			,isShowPagination:false
			,isShowSettingButton:false
			,columns:[
				{text:"角色",name:"roleName"}
			]
		});
		
	}
	
	function reset() {
		schPanel.reset();
		grid.reload();
	}
	
	function loadUserRole(){
		if(schUsername){	
			Action.post(ctx + 'listUserRRole.do',{usernameSch:schUsername},function(e){
				if(e.rows){
					var rows = e.rows;
					for(var i=0,len=rows.length;i<len;i++){
						// 勾选已有的角色
						grid.selectRecord(rows[i].roleId);
					}
				}else{
					FDWindow.alert('加载角色出错');
				}
			});
		}
	}
	
	return {
		show:function(username,callback) {
			schUsername = username;
			if(username){
				init(callback);
				win.setTitle('设置<strong>'+username+'</strong>的角色');
				reset();
				loadUserRole();
				win.show();
			}
		}
		,hide:function() {
			win.hide();
		}
	};
	
	
})();
